import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/models.dart';
import '../services/services.dart';
import '../constants/constants.dart';

import 'player_screen.dart';
import 'music_list_screen.dart';
import 'favorites_screen.dart';
import 'history_screen.dart';
import 'settings_screen.dart';

/// 主页面
/// 应用的主要入口，包含底部导航和各个功能模块
class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> with TickerProviderStateMixin {
  late AnimationController _fadeController;
  late Animation<double> _fadeAnimation;

  int _currentIndex = 0;
  List<Music> _recentMusic = [];
  List<Music> _favoriteMusic = [];
  PlayStatistics? _statistics;
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _initAnimations();
    _loadHomeData();
  }

  /// 初始化动画
  void _initAnimations() {
    _fadeController = AnimationController(
      duration: AppTheme.animationDurationMedium,
      vsync: this,
    );
    _fadeAnimation = Tween<double>(
      begin: 0.0,
      end: 1.0,
    ).animate(CurvedAnimation(
      parent: _fadeController,
      curve: Curves.easeInOut,
    ));
  }

  /// 加载主页数据
  Future<void> _loadHomeData() async {
    try {
      final musicLibraryService =
          Provider.of<MusicLibraryService>(context, listen: false);
      // final databaseService = Provider.of<DatabaseService>(context, listen: false);

      // 并行加载数据
      final results = await Future.wait([
        Future.value(musicLibraryService.musicLibrary.take(10).toList()),
        Future.value(musicLibraryService.musicLibrary
            .where((m) => m.isFavorite)
            .take(10)
            .toList()),
        Future.value(null),
      ]);

      setState(() {
        _recentMusic = results[0] as List<Music>;
        _favoriteMusic = results[1] as List<Music>;
        _statistics = results[2] as PlayStatistics?;
        _isLoading = false;
      });

      _fadeController.forward();
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      _showErrorSnackBar('加载数据失败: $e');
    }
  }

  /// 显示错误提示
  void _showErrorSnackBar(String message) {
    ScaffoldMessenger.of(context).showSnackBar(
      SnackBar(
        content: Text(message),
        backgroundColor: AppTheme.errorColor,
      ),
    );
  }

  @override
  void dispose() {
    _fadeController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: const BoxDecoration(
          gradient: AppTheme.backgroundGradientDark,
        ),
        child: SafeArea(
          child: Column(
            children: [
              // 主要内容区域
              Expanded(
                child: _buildCurrentPage(),
              ),

              // 迷你播放器
              _buildMiniPlayer(),

              // 底部导航栏
              _buildBottomNavigation(),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建当前页面
  Widget _buildCurrentPage() {
    switch (_currentIndex) {
      case 0:
        return _buildHomePage();
      case 1:
        return const MusicListScreen();
      case 2:
        return const FavoritesScreen();
      case 3:
        return const HistoryScreen();
      case 4:
        return const SettingsScreen();
      default:
        return _buildHomePage();
    }
  }

  /// 构建主页内容
  Widget _buildHomePage() {
    if (_isLoading) {
      return _buildLoadingState();
    }

    return FadeTransition(
      opacity: _fadeAnimation,
      child: SingleChildScrollView(
        padding: const EdgeInsets.all(AppTheme.spacingMedium),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 顶部问候和搜索
            _buildHeader(),

            const SizedBox(height: AppTheme.spacingLarge),

            // 统计卡片
            if (_statistics != null) ...[
              _buildStatisticsCard(),
              const SizedBox(height: AppTheme.spacingLarge),
            ],

            // 快速操作
            _buildQuickActions(),

            const SizedBox(height: AppTheme.spacingLarge),

            // 最近播放
            if (_recentMusic.isNotEmpty) ...[
              _buildSectionHeader('最近播放', () {
                Navigator.of(context).push(
                  MaterialPageRoute(
                    builder: (context) => const HistoryScreen(),
                  ),
                );
              }),
              const SizedBox(height: AppTheme.spacingMedium),
              _buildHorizontalMusicList(_recentMusic),
              const SizedBox(height: AppTheme.spacingLarge),
            ],

            // 我的收藏
            if (_favoriteMusic.isNotEmpty) ...[
              _buildSectionHeader('我的收藏', () {
                Navigator.of(context).push(
                  MaterialPageRoute(
                    builder: (context) => const FavoritesScreen(),
                  ),
                );
              }),
              const SizedBox(height: AppTheme.spacingMedium),
              _buildHorizontalMusicList(_favoriteMusic),
              const SizedBox(height: AppTheme.spacingLarge),
            ],

            // 推荐音乐（基于播放历史）
            _buildRecommendations(),

            const SizedBox(height: AppTheme.spacingXL),
          ],
        ),
      ),
    );
  }

  /// 构建加载状态
  Widget _buildLoadingState() {
    return const Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          CircularProgressIndicator(
            valueColor: AlwaysStoppedAnimation<Color>(AppTheme.primaryColor),
          ),
          SizedBox(height: AppTheme.spacingMedium),
          Text(
            '正在加载...',
            style: TextStyle(
              fontSize: AppTheme.fontSizeMedium,
              color: AppTheme.textSecondaryDark,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建头部
  Widget _buildHeader() {
    return Row(
      children: [
        Expanded(
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                _getGreeting(),
                style: const TextStyle(
                  fontSize: AppTheme.fontSizeXL,
                  fontWeight: FontWeight.bold,
                  color: AppTheme.textPrimaryDark,
                ),
              ),
              const SizedBox(height: AppTheme.spacingXS),
              const Text(
                '享受你的音乐时光',
                style: TextStyle(
                  fontSize: AppTheme.fontSizeMedium,
                  color: AppTheme.textSecondaryDark,
                ),
              ),
            ],
          ),
        ),
        IconButton(
          onPressed: () {
            // TODO: 实现搜索功能
          },
          icon: const Icon(
            Icons.search,
            color: AppTheme.textPrimaryDark,
            size: AppTheme.iconSizeLarge,
          ),
        ),
      ],
    );
  }

  /// 构建统计卡片
  Widget _buildStatisticsCard() {
    return Container(
      padding: const EdgeInsets.all(AppTheme.spacingLarge),
      decoration: BoxDecoration(
        gradient: AppTheme.primaryGradient,
        borderRadius: BorderRadius.circular(AppTheme.radiusLarge),
        boxShadow: AppTheme.elevatedShadow,
      ),
      child: Column(
        children: [
          const Row(
            children: [
              Icon(
                Icons.equalizer,
                color: Colors.white,
                size: AppTheme.iconSizeLarge,
              ),
              SizedBox(width: AppTheme.spacingMedium),
              Expanded(
                child: Text(
                  '播放统计',
                  style: TextStyle(
                    fontSize: AppTheme.fontSizeLarge,
                    fontWeight: FontWeight.bold,
                    color: Colors.white,
                  ),
                ),
              ),
            ],
          ),
          const SizedBox(height: AppTheme.spacingLarge),
          Row(
            children: [
              Expanded(
                child: _buildStatItem(
                  '总播放时长',
                  _statistics!.formattedTotalPlayTime,
                  Icons.access_time,
                ),
              ),
              Expanded(
                child: _buildStatItem(
                  '播放次数',
                  '${_statistics!.totalPlayCount}',
                  Icons.play_circle,
                ),
              ),
            ],
          ),
          const SizedBox(height: AppTheme.spacingMedium),
          Row(
            children: [
              Expanded(
                child: _buildStatItem(
                  '今日播放',
                  _statistics!.formattedTodayPlayTime,
                  Icons.today,
                ),
              ),
              Expanded(
                child: _buildStatItem(
                  '平均时长',
                  '${(_statistics!.totalPlayTime / _statistics!.totalPlayCount / 60000).toStringAsFixed(1)}分钟',
                  Icons.trending_up,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建统计项
  Widget _buildStatItem(String label, String value, IconData icon) {
    return Column(
      children: [
        Icon(
          icon,
          color: Colors.white.withOpacity(0.8),
          size: AppTheme.iconSizeMedium,
        ),
        const SizedBox(height: AppTheme.spacingSmall),
        Text(
          value,
          style: const TextStyle(
            fontSize: AppTheme.fontSizeLarge,
            fontWeight: FontWeight.bold,
            color: Colors.white,
          ),
        ),
        const SizedBox(height: AppTheme.spacingXS),
        Text(
          label,
          style: TextStyle(
            fontSize: AppTheme.fontSizeSmall,
            color: Colors.white.withOpacity(0.8),
          ),
          textAlign: TextAlign.center,
        ),
      ],
    );
  }

  /// 构建快速操作
  Widget _buildQuickActions() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        const Text(
          '快速操作',
          style: TextStyle(
            fontSize: AppTheme.fontSizeLarge,
            fontWeight: FontWeight.bold,
            color: AppTheme.textPrimaryDark,
          ),
        ),
        const SizedBox(height: AppTheme.spacingMedium),
        Row(
          children: [
            Expanded(
              child: _buildQuickActionCard(
                '浏览音乐',
                Icons.library_music,
                AppTheme.primaryColor,
                () {
                  setState(() {
                    _currentIndex = 1;
                  });
                },
              ),
            ),
            const SizedBox(width: AppTheme.spacingMedium),
            Expanded(
              child: _buildQuickActionCard(
                '我的收藏',
                Icons.favorite,
                AppTheme.errorColor,
                () {
                  setState(() {
                    _currentIndex = 2;
                  });
                },
              ),
            ),
          ],
        ),
        const SizedBox(height: AppTheme.spacingMedium),
        Row(
          children: [
            Expanded(
              child: _buildQuickActionCard(
                '播放历史',
                Icons.history,
                AppTheme.warningColor,
                () {
                  setState(() {
                    _currentIndex = 3;
                  });
                },
              ),
            ),
            const SizedBox(width: AppTheme.spacingMedium),
            Expanded(
              child: _buildQuickActionCard(
                '扫描音乐',
                Icons.refresh,
                AppTheme.successColor,
                _scanMusicLibrary,
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// 构建快速操作卡片
  Widget _buildQuickActionCard(
    String title,
    IconData icon,
    Color color,
    VoidCallback onTap,
  ) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        padding: const EdgeInsets.all(AppTheme.spacingXS),
        decoration: BoxDecoration(
          color: AppTheme.surfaceDark,
          borderRadius: BorderRadius.circular(AppTheme.radiusMedium),
          border: Border.all(
            color: color.withOpacity(0.3),
            width: 1,
          ),
        ),
        child: Column(
          children: [
            Container(
              width: 40,
              height: 40,
              decoration: BoxDecoration(
                color: color.withOpacity(0.2),
                borderRadius: BorderRadius.circular(AppTheme.radiusMedium),
              ),
              child: Icon(
                icon,
                color: color,
                size: AppTheme.iconSizeMedium,
              ),
            ),
            const SizedBox(height: 4),
            Text(
              title,
              style: const TextStyle(
                fontSize: AppTheme.fontSizeSmall - 1,
                fontWeight: FontWeight.w500,
                color: AppTheme.textPrimaryDark,
              ),
              textAlign: TextAlign.center,
              maxLines: 1,
              overflow: TextOverflow.ellipsis,
            ),
          ],
        ),
      ),
    );
  }

  /// 构建节标题
  Widget _buildSectionHeader(String title, VoidCallback onTap) {
    return Row(
      children: [
        Expanded(
          child: Text(
            title,
            style: const TextStyle(
              fontSize: AppTheme.fontSizeLarge,
              fontWeight: FontWeight.bold,
              color: AppTheme.textPrimaryDark,
            ),
          ),
        ),
        TextButton(
          onPressed: onTap,
          child: const Text(
            '查看全部',
            style: TextStyle(
              fontSize: AppTheme.fontSizeSmall,
              color: AppTheme.primaryColor,
            ),
          ),
        ),
      ],
    );
  }

  /// 构建水平音乐列表
  Widget _buildHorizontalMusicList(List<Music> musicList) {
    return SizedBox(
      height: 180,
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        itemCount: musicList.length,
        itemBuilder: (context, index) {
          final music = musicList[index];
          return Container(
            width: 140,
            margin: EdgeInsets.only(
              right: index < musicList.length - 1 ? AppTheme.spacingMedium : 0,
            ),
            child: _buildMusicCard(music),
          );
        },
      ),
    );
  }

  /// 构建音乐卡片
  Widget _buildMusicCard(Music music) {
    return GestureDetector(
      onTap: () => _playMusic(music),
      child: Container(
        decoration: BoxDecoration(
          color: AppTheme.surfaceDark,
          borderRadius: BorderRadius.circular(AppTheme.radiusMedium),
          border: Border.all(
            color: AppTheme.primaryColor.withOpacity(0.3),
            width: 1,
          ),
        ),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 封面
            Container(
              height: 100,
              decoration: const BoxDecoration(
                borderRadius: BorderRadius.vertical(
                  top: Radius.circular(AppTheme.radiusMedium),
                ),
                gradient: AppTheme.primaryGradient,
              ),
              child: ClipRRect(
                borderRadius: const BorderRadius.vertical(
                  top: Radius.circular(AppTheme.radiusMedium),
                ),
                child: music.coverArt != null
                    ? Image.asset(
                        music.coverArt!,
                        width: double.infinity,
                        height: 100,
                        fit: BoxFit.cover,
                        errorBuilder: (context, error, stackTrace) {
                          return _buildDefaultCover();
                        },
                      )
                    : _buildDefaultCover(),
              ),
            ),

            // 信息
            Expanded(
              child: Padding(
                padding: const EdgeInsets.all(AppTheme.spacingXS),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      music.title,
                      style: const TextStyle(
                        fontSize: AppTheme.fontSizeXS,
                        fontWeight: FontWeight.w600,
                        color: AppTheme.textPrimaryDark,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 2),
                    Text(
                      music.artist,
                      style: const TextStyle(
                        fontSize: AppTheme.fontSizeXS - 1,
                        color: AppTheme.textSecondaryDark,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 2),
                    Text(
                      music.formattedDuration,
                      style: const TextStyle(
                        fontSize: AppTheme.fontSizeXS - 1,
                        color: AppTheme.textHintDark,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建默认封面
  Widget _buildDefaultCover() {
    return Container(
      width: double.infinity,
      height: 100,
      decoration: const BoxDecoration(
        gradient: AppTheme.primaryGradient,
      ),
      child: const Icon(
        Icons.music_note,
        color: Colors.white,
        size: AppTheme.iconSizeLarge,
      ),
    );
  }

  /// 构建推荐音乐
  Widget _buildRecommendations() {
    //  实现基于播放历史的推荐算法
    return Container(
      padding: const EdgeInsets.all(AppTheme.spacingLarge),
      decoration: BoxDecoration(
        color: AppTheme.surfaceDark,
        borderRadius: BorderRadius.circular(AppTheme.radiusMedium),
        border: Border.all(
          color: AppTheme.primaryColor.withOpacity(0.3),
          width: 1,
        ),
      ),
      child: Column(
        children: [
          const Row(
            children: [
              Icon(
                Icons.recommend,
                color: AppTheme.primaryColor,
                size: AppTheme.iconSizeMedium,
              ),
              SizedBox(width: AppTheme.spacingSmall),
              Text(
                '为你推荐',
                style: TextStyle(
                  fontSize: AppTheme.fontSizeLarge,
                  fontWeight: FontWeight.bold,
                  color: AppTheme.textPrimaryDark,
                ),
              ),
            ],
          ),
          const SizedBox(height: AppTheme.spacingMedium),
          const Text(
            '基于你的播放历史，我们会为你推荐\n更多你可能喜欢的音乐',
            style: TextStyle(
              fontSize: AppTheme.fontSizeMedium,
              color: AppTheme.textSecondaryDark,
            ),
            textAlign: TextAlign.center,
          ),
          const SizedBox(height: AppTheme.spacingMedium),
          ElevatedButton(
            onPressed: () {
              setState(() {
                _currentIndex = 1;
              });
            },
            child: const Text('浏览音乐库'),
          ),
        ],
      ),
    );
  }

  /// 构建迷你播放器
  Widget _buildMiniPlayer() {
    return Consumer<AudioPlayerService>(
      builder: (context, audioService, child) {
        if (audioService.currentMusic == null) {
          return const SizedBox.shrink();
        }

        return GestureDetector(
          onTap: () {
            Navigator.of(context).push(
              MaterialPageRoute(
                builder: (context) => const PlayerScreen(),
              ),
            );
          },
          child: Column(
            children: [
              // 顶部细进度条
              LinearProgressIndicator(
                value: audioService.progressPercentage
                    .clamp(0.0, 1.0)
                    .toDouble(),
                minHeight: 3,
                color: AppTheme.primaryColor,
                backgroundColor: AppTheme.primaryColor.withOpacity(0.15),
              ),
              Container(
                height: 76,
                margin: const EdgeInsets.symmetric(
                  horizontal: AppTheme.spacingSmall,
                  vertical: AppTheme.spacingSmall,
                ),
                decoration: BoxDecoration(
                  color: AppTheme.surfaceDark,
                  borderRadius: BorderRadius.circular(AppTheme.radiusLarge),
                  border: Border.all(
                    color: AppTheme.primaryColor.withOpacity(0.5),
                    width: 1,
                  ),
                ),
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    // 基础信息行
                    Row(
                      children: [
                        // 封面
                        Container(
                          width: 64,
                          height: 64,
                          margin: const EdgeInsets.all(AppTheme.spacingXS),
                          decoration: BoxDecoration(
                            borderRadius: BorderRadius.circular(AppTheme.radiusSmall),
                            gradient: AppTheme.primaryGradient,
                          ),
                          child: ClipRRect(
                            borderRadius: BorderRadius.circular(AppTheme.radiusSmall),
                            child: audioService.currentMusic!.coverArt != null
                                ? Image.asset(
                                    audioService.currentMusic!.coverArt!,
                                    fit: BoxFit.cover,
                                    errorBuilder: (context, error, stackTrace) {
                                      return const Icon(
                                        Icons.music_note,
                                        color: Colors.white,
                                        size: AppTheme.iconSizeMedium,
                                      );
                                    },
                                  )
                                : const Icon(
                                    Icons.music_note,
                                    color: Colors.white,
                                    size: AppTheme.iconSizeMedium,
                                  ),
                          ),
                        ),

                        // 标题与歌手
                        Expanded(
                          child: Padding(
                            padding: const EdgeInsets.symmetric(
                              horizontal: AppTheme.spacingSmall,
                            ),
                            child: Column(
                              mainAxisAlignment: MainAxisAlignment.center,
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Text(
                                  audioService.currentMusic!.title,
                                  style: const TextStyle(
                                    fontSize: AppTheme.fontSizeMedium,
                                    fontWeight: FontWeight.bold,
                                    color: AppTheme.textPrimaryDark,
                                  ),
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                ),
                                const SizedBox(height: 2),
                                Text(
                                  audioService.currentMusic!.artist,
                                  style: const TextStyle(
                                    fontSize: AppTheme.fontSizeXS,
                                    color: AppTheme.textSecondaryDark,
                                  ),
                                  maxLines: 1,
                                  overflow: TextOverflow.ellipsis,
                                ),
                              ],
                            ),
                          ),
                        ),

                        // 下一首按钮（与图层中心播放键配合）
                        IconButton(
                          onPressed:
                              audioService.hasNext ? audioService.playNext : null,
                          icon: const Icon(
                            Icons.skip_next,
                            color: AppTheme.textSecondaryDark,
                            size: AppTheme.iconSizeMedium,
                          ),
                        ),
                      ],
                    ),

                    // 居中的播放/暂停圆形按钮
                    Container(
                      width: 54,
                      height: 54,
                      decoration: BoxDecoration(
                        color: AppTheme.backgroundDark,
                        shape: BoxShape.circle,
                        border: Border.all(
                          color: AppTheme.primaryColor.withOpacity(0.7),
                          width: 2,
                        ),
                      ),
                      child: IconButton(
                        onPressed: () {
                          if (audioService.isPlaying) {
                            audioService.pause();
                          } else {
                            audioService.resume();
                          }
                        },
                        icon: Icon(
                          audioService.isPlaying ? Icons.pause : Icons.play_arrow,
                          color: AppTheme.primaryColor,
                          size: AppTheme.iconSizeLarge,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  /// 构建底部导航栏
  Widget _buildBottomNavigation() {
    return Container(
      decoration: BoxDecoration(
        color: AppTheme.surfaceDark,
        border: Border(
          top: BorderSide(
            color: AppTheme.primaryColor.withOpacity(0.3),
            width: 1,
          ),
        ),
      ),
      child: BottomNavigationBar(
        currentIndex: _currentIndex,
        onTap: (index) {
          setState(() {
            _currentIndex = index;
          });
        },
        type: BottomNavigationBarType.fixed,
        backgroundColor: Colors.transparent,
        elevation: 0,
        selectedItemColor: AppTheme.primaryColor,
        unselectedItemColor: AppTheme.textSecondaryDark,
        selectedFontSize: AppTheme.fontSizeXS,
        unselectedFontSize: AppTheme.fontSizeXS,
        items: const [
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: '首页',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.library_music),
            label: '音乐库',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.favorite),
            label: '收藏',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.history),
            label: '历史',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.settings),
            label: '设置',
          ),
        ],
      ),
    );
  }

  /// 获取问候语
  String _getGreeting() {
    final hour = DateTime.now().hour;
    if (hour < 6) {
      return '夜深了';
    } else if (hour < 12) {
      return '早上好';
    } else if (hour < 18) {
      return '下午好';
    } else {
      return '晚上好';
    }
  }

  /// 播放音乐
  void _playMusic(Music music) {
    final audioService =
        Provider.of<AudioPlayerService>(context, listen: false);

    // 播放单首音乐
    audioService.playMusic(music);

    // 导航到播放页面
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => const PlayerScreen(),
      ),
    );
  }

  /// 扫描音乐库
  void _scanMusicLibrary() async {
    try {
      final musicLibraryService =
          Provider.of<MusicLibraryService>(context, listen: false);

      // 显示加载对话框
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) => const AlertDialog(
          backgroundColor: AppTheme.surfaceDark,
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              CircularProgressIndicator(
                valueColor:
                    AlwaysStoppedAnimation<Color>(AppTheme.primaryColor),
              ),
              SizedBox(height: AppTheme.spacingMedium),
              Text(
                '正在扫描音乐库...',
                style: TextStyle(color: AppTheme.textPrimaryDark),
              ),
            ],
          ),
        ),
      );

      await musicLibraryService.scanLocalMusic();

      if (mounted) {
        Navigator.of(context).pop(); // 关闭加载对话框
      }

      // 重新加载数据
      _loadHomeData();

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('音乐库扫描完成'),
            backgroundColor: AppTheme.successColor,
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        Navigator.of(context).pop(); // 关闭加载对话框
      }
      _showErrorSnackBar('扫描失败: $e');
    }
  }
}
